﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace bypy
{
    class BD
    {
        private const string DISK_URL = "https://c.pcs.baidu.com/rest/2.0/pcs/file?method=upload&access_token={0}&path={1}";
        private const string DISK_DIR = "%2Fapps%2Fbypy";

        internal static string Upload(string token, string filepath, string filename)
        {
            string resp;
            SetSSl();
            HttpWebRequest request = null;
            WebResponse response = null;
            try
            {
                var date = DateTime.Now;
                var path = string.Format("{0}%2F{1}", DISK_DIR, filename);
                var url = string.Format(DISK_URL, token, path);

                MemoryStream ms = new MemoryStream();
                var boundary = "----" + DateTime.Now.Ticks.ToString("x");
                var formdata = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                var fileBytes = Encoding.ASCII.GetBytes(formdata);
                ms.Write(fileBytes, 0, fileBytes.Length);
                byte[] bytes = File.ReadAllBytes(filepath);
                ms.Write(bytes, 0, bytes.Length);
                var endBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                ms.Write(endBytes, 0, endBytes.Length);

                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Timeout = 30000;
                request.ReadWriteTimeout = 30000;
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                request.ContentLength = ms.Length;
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                request.KeepAlive = true;
                request.UserAgent = "pan.baidu.com"; // "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";

                ms.Position = 0;
                Stream requestStream = request.GetRequestStream();
                byte[] buff = new byte[8192];
                int bytesRead = 0;
                while ((bytesRead = ms.Read(buff, 0, buff.Length)) != 0)
                {
                    requestStream.Write(buff, 0, bytesRead);
                }
                ms.Close();

                response = request.GetResponse();
            }
            catch (WebException e)
            {
                resp = string.Format("{\"error_msg\":\"{0}\"}", e.Message);
                response = e.Response;
            }
            catch (Exception e)
            {
                resp = string.Format("{\"error_msg\":\"{0}\"}", e.Message);
            }
            finally
            {
                if (response != null)
                {
                    using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        resp = stream.ReadToEnd();
                    }
                    response.Close();
                }
                else
                {
                    resp = string.Format("{\"error_msg\":\"{0}\"}", "Duang error");
                }
                if (request != null) request.Abort();
            }
            return resp;
        }
        internal static void SetSSl()
        {
            try
            {
                ServicePointManager.Expect100Continue = false;
                ServicePointManager.DefaultConnectionLimit = 512;
                ServicePointManager.CheckCertificateRevocationList = false;
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                /* Ssl3(48 - 0x30) Tls(192 - 0xC0) Tls11(768 - 0x300) missing on Framework 4.0 Tls12(3072 - 0xC00) missing on Framework 4.0 */
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)0x300 | (SecurityProtocolType)0xC00;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            }
            catch (Exception e)
            {
                Console.WriteLine("System not support Tls11 or Tls12, " + e.Message);
                try
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                }
                catch { }
            }
        }
    }
}
